const express = require('express');
const lbs = require("./index/lbs/lbs")
const jlts = require("./index/jlts/jlts")
const products = require("./index/products/products")
const details = require("./index/details/details")
const users = require("./user/users/users")
const ygclass = require("./index/classifications/classifocations")
const fls = require("./index/fl/fls")
const cors = require('cors');
const {
    urlencoded
} = require('express');
const app = express()
app.use(cors({
    origin: '*'
}))
app.listen(3000, () => {
    console.log("server is running");
})
app.use(express.static('./public'))
app.use(urlencoded({
    extended: false
}))

// 首页轮播图接口
app.get('/index_lbs', (req, res, next) => {
    lbs.find({}, {
        _id: 0
    }, (err, doc) => {
        if (err) {
            next(err)
            return
        }
        res.send({
            data: doc
        })
    })
})
// 首页精灵图
app.get('/index_jlts', (req, res, next) => {
    jlts.find({}, {
        _id: 0
    }, (err, doc) => {
        if (err) {
            next(err)
            return
        }
        res.send({
            data: doc
        })
    })
})

//首页商品
app.get('/index_products', (req, res, next) => {
    let page = req.query.page
    if (!page) {
        console.log(page);
        page = 1
    }
    products.find().skip((page * 1 - 1) * 5).limit(5).exec((err, doc) => {
        res.send({
            data: doc
        })
    })

})
//商品详情页
app.get('/index_details', (req, res, next) => {
    let goodsId = req.query.goodsId
    details.find({
        goodsId
    }, {}, (err, doc) => {
        if (err) {
            next(err)
            return
        }
        res.send({
            data: doc
        })
    })


})

//用户登录接口
app.post('/login', (req, res, next) => {
    let name = req.body.name
    let pwd = req.body.pwd
    users.find({uid:name,pwd}, (err, doc) => {
        if (err) {
            next(err)
            return
        }
        if(doc.length==0)
        {
            res.send({code:201,msg:'登录失败'})
            return
        }
        res.send({code:200,msg:'登录成功',data:doc})
    })

})

//分类左侧侧边栏
app.get('/index_listclass',(req,res,next)=>{
    ygclass.find({},(err,doc)=>{
        if(err)
        {
            next(err)
            return 
        }
        res.send(doc)
    })
})
//分类右侧
app.get('/index_pp',(req,res,next)=>{
    let id = req.query.id
    if(!id)id=1
    fls.find({id},(err,doc)=>{
        if(err)
        {
            next(err)
            return
        }
        res.send(doc)
    })
})
//错误路由拦截
app.use((err, req, res, next) => {
    if (err) {
        console.log(err);
        res.status(500).send({
            code: 500,
            msg: "服务器错误"
        })
    }
})